package com.canbot.u05.activity.shoppingGuide.codeMarketing;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.adapter.BasePageAdapter;
import com.canbot.u05.bean.codeMarketing.CodeMarketingInfo;
import com.canbot.u05.bean.guide.MapVoiceAndEyes;
import com.canbot.u05.glide.GlideApp;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.StatusBarUtil;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.utils.qr.QRCodeTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CodeMainActivity extends BaseActivityNoTitle implements View.OnClickListener {

        @BindView(R.id.code_iv_back)
        Button codeIvBack;

        @BindView(R.id.code_iv_set)
        Button codeIvSet;

        @BindView(R.id.code_iv_1)
        ImageView codeIv1;

        @BindView(R.id.code_tv_1)
        TextView codeTv1;

        @BindView(R.id.code_ll_1)
        LinearLayout codeLl1;

        @BindView(R.id.code_iv_2)
        ImageView codeIv2;

        @BindView(R.id.code_tv_2)
        TextView codeTv2;

        @BindView(R.id.code_ll_2)
        LinearLayout codeLl2;

        @BindView(R.id.code_iv_3)
        ImageView codeIv3;

        @BindView(R.id.code_tv_3)
        TextView codeTv3;

        @BindView(R.id.code_ll_3)
        LinearLayout codeLl3;

        @BindView(R.id.code_bg)
        ImageView codeBg;

        @BindView(R.id.code_main_rl)
        RelativeLayout codeMainRl;

        @BindView(R.id.tv_title)
        TextView tvTitle;

        @BindView(R.id.code_bg_vp)
        ViewPager codeBgVp;

        private PopupWindow popupWindow;

        private Dialog hintDialog;

        private boolean mIsDel;

        private ToastTools toastTools;

        private boolean isOnCreate;

        private int currentPosition;

        private List<String> imagePaths;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_code_main);
                ButterKnife.bind(this);
                toastTools = ToastTools.newInstance(this);
                isOnCreate = true;
                tvTitle.setSelected(true);
                MapVoiceAndEyes.CODE_MARKETING[(int) (Math.random() * 2) + 10].playMapVoiceAndEyes();
                codeIvBack.post(new Runnable() {
                        @Override
                        public void run() {
                                getMarketingData();
                        }
                });
        }
        private Dialog dialogLoading;
        private void getMarketingData() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                String url = IpMsgConst.HTTP_URL_CHEST + "codeMarketingAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", 1);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                CodeMarketingInfo parseObject = null;
                                if (!TextUtils.isEmpty(result)) {
                                        try {
                                                parseObject = JSON.parseObject(result, CodeMarketingInfo.class);
                                        }
                                        catch (Exception e) {
                                                e.printStackTrace();
                                        }
                                }
                                CodeDataHelper.getInstance().setCodeMarketingSave(parseObject);
                                initData();

                        }

                        @Override
                        public void onFailure() {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                toastTools.showText(getString(R.string.service_error_hint));
                                finish();
                        }
                });
        }

        private void delMarketingData() {
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.loading));
                CodeMarketingInfo info = CodeDataHelper.getInstance().getCodeMarketingInfo();
                String url = IpMsgConst.HTTP_URL_CHEST + "codeMarketingAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", 2);
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                CodeDataHelper.getInstance().setCodeMarketingSave(null);
                                initData();

                        }

                        @Override
                        public void onFailure() {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                                toastTools.showText(getString(R.string.service_error_hint));
                                finish();
                        }
                });
        }



        @Override
        protected void onResume() {
                super.onResume();
                if (!isOnCreate) {
                        initData();
                }
                isOnCreate = false;
        }

        private void initData() {
                runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                                codeLl1.setVisibility(View.GONE);
                                codeLl2.setVisibility(View.GONE);
                                codeLl3.setVisibility(View.GONE);
                                tvTitle.setText(null);
                                CodeMarketingInfo marketingInfo = CodeDataHelper.getInstance().getCodeMarketingSave();
                                if (marketingInfo == null) {
                                        showHintDialog(false);
                                        return;
                                }
                                if (marketingInfo.getType() == CodeMarketingInfo.TYPE_FREEDOM) {
                                        final List<String> imagePaths = marketingInfo.getImagePaths();
                                        codeBgVp.setVisibility(View.VISIBLE);
                                        codeBg.setVisibility(View.GONE);
                                        initViewPage(imagePaths);
                                        return;
                                }
                                String title = marketingInfo.getTitle();
                                tvTitle.setText(title);
                                codeBg.setVisibility(View.VISIBLE);
                                codeBgVp.setVisibility(View.GONE);
                                codeBg.setImageResource(CodeDataHelper.CODE_DRAWS.get(marketingInfo.getBgResourcesIndex()));
                                setCode(marketingInfo);
                        }


                });
        }

        private void initViewPage(final List<String> imagePaths) {
                this.imagePaths = imagePaths;
                codeBgVp.setAdapter(new BasePageAdapter(R.layout.code_bg_item_iv, imagePaths.size()) {
                        @Override
                        public void setPageView(View inflate, int position, int layoutID, Object o) {
                                ImageView imageView = (ImageView) inflate.findViewById(R.id.imageView);
                                GlideApp.with(CodeMainActivity.this).clear(imageView);
                                GlideApp.with(CodeMainActivity.this)
                                        .asDrawable()
                                        .load(IpMsgConst.HTTP_URL_CHEST + imagePaths.get(position).replace("/uupic/","/uupic_thumb/"))
                                        .thumbnail(0.1f)
                                        .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                                        .skipMemoryCache(false)
                                        .placeholder(R.drawable.sales_banner01)//占位图
                                        .error(R.drawable.sales_banner01)
                                        .into(imageView);
                        }
                });

                codeBgVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {
                                currentPosition = position;
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                });

                codeBgVp.setOnTouchListener(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                                switch (event.getAction()) {
                                        case MotionEvent.ACTION_DOWN:
                                                codeBgVp.removeCallbacks(runnable);
                                                break;
                                        case MotionEvent.ACTION_UP:
                                        case MotionEvent.ACTION_CANCEL:
                                                codeBgVp.removeCallbacks(runnable);
                                                codeBgVp.postDelayed(runnable, 10 * 1000);
                                                break;
                                }
                                return false;
                        }
                });
                codeBgVp.removeCallbacks(runnable);
                codeBgVp.postDelayed(runnable, 10 * 1000);
        }

        private Runnable runnable = new Runnable() {
                @Override
                public void run() {
                        currentPosition++;
                        if (currentPosition >= imagePaths.size()) {
                                currentPosition = 0;
                        }
                        codeBgVp.setCurrentItem(currentPosition, true);
                        codeBgVp.postDelayed(this, 10 * 1000);
                }
        };

        private void setCode(CodeMarketingInfo info) {
                String codeTitle1 = info.getCodeInfo1().getCodeTitle();
                String codeData1 = info.getCodeInfo1().getCodeData();
                String codeTitle2 = info.getCodeInfo2().getCodeTitle();
                String codeData2 = info.getCodeInfo2().getCodeData();
                String codeTitle3 = info.getCodeInfo3().getCodeTitle();
                String codeData3 = info.getCodeInfo3().getCodeData();
                switch (info.getType()) {
                        case CodeMarketingInfo.TYPE_COUNT_ONE:
                                codeLl1.setVisibility(View.VISIBLE);
                                Bitmap resource = BitmapFactory.decodeResource(getResources(), R.drawable.uu_logo_code);
                                Bitmap image = QRCodeTools.createImage(codeData1, 400, 400, resource);
                                codeIv1.setImageBitmap(image);
                                codeTv1.setText(codeTitle1);
                                break;
                        case CodeMarketingInfo.TYPE_COUNT_TWO:
                                codeLl1.setVisibility(View.VISIBLE);
                                codeLl2.setVisibility(View.VISIBLE);
                                resource = BitmapFactory.decodeResource(getResources(), R.drawable.uu_logo_code);
                                image = QRCodeTools.createImage(codeData1, 400, 400, resource);
                                codeIv1.setImageBitmap(image);
                                codeTv1.setText(codeTitle1);
                                image = QRCodeTools.createImage(codeData2, 400, 400, resource);
                                codeIv2.setImageBitmap(image);
                                codeTv2.setText(codeTitle2);
                                break;
                        case CodeMarketingInfo.TYPE_COUNT_THREE:
                                codeLl1.setVisibility(View.VISIBLE);
                                codeLl2.setVisibility(View.VISIBLE);
                                codeLl3.setVisibility(View.VISIBLE);
                                resource = BitmapFactory.decodeResource(getResources(), R.drawable.uu_logo_code);
                                image = QRCodeTools.createImage(codeData1, 400, 400, resource);
                                codeIv1.setImageBitmap(image);
                                codeTv1.setText(codeTitle1);
                                image = QRCodeTools.createImage(codeData2, 400, 400, resource);
                                codeIv2.setImageBitmap(image);
                                codeTv2.setText(codeTitle2);
                                image = QRCodeTools.createImage(codeData3, 400, 400, resource);
                                codeIv3.setImageBitmap(image);
                                codeTv3.setText(codeTitle3);
                                break;
                }
        }

        @OnClick({R.id.code_iv_back, R.id.code_iv_set})
        public void onViewClicked(View view) {
                switch (view.getId()) {
                        case R.id.code_iv_back:
                                finish();
                                break;
                        case R.id.code_iv_set:
                                showPopupWindow();
                                break;
                }
        }

        /**
         * 提示Dialog
         */
        private void showHintDialog(boolean isDel) {
                if (hintDialog == null) {
                        hintDialog = new Dialog(this, R.style.MyDialogStyle);
                        hintDialog.setContentView(R.layout.guide_dialog_hint);
                        hintDialog.setCancelable(false);
                        Button sure = (Button) hintDialog
                                .findViewById(R.id.guide_dialog_hint_sure);
                        sure.setText(getString(R.string.sure));
                        sure.setOnClickListener(this);
                        Button move = ((Button) hintDialog
                                .findViewById(R.id.guide_dialog_hint_move));
                        move.setText(getString(R.string.cancel));
                        move.setOnClickListener(this);
                }
                TextView textView = (TextView) hintDialog.findViewById(R.id.guide_dialog_tv);
                textView.setText(isDel ? "是否确定删除定制数据?" : "当前无任务,是否开始新建任务?");
                StatusBarUtil.hideVirtualKey(hintDialog);
                this.mIsDel = isDel;
                hintDialog.show();
        }


        private void showPopupWindow() {
                if (popupWindow == null) {
                        View inflate = View.inflate(this, R.layout.code_set_pop, null);
                        inflate.findViewById(R.id.code_reset_ll).setOnClickListener(this);
                        inflate.findViewById(R.id.code_del_ll).setOnClickListener(this);
                        popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        popupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                        popupWindow.setOutsideTouchable(true); //设置 popupWindow外面可点击
                        popupWindow.setBackgroundDrawable(new ColorDrawable());
                        //给popupWindow设置一个背景
                        //                popupWindow.setFocusable(true); //可以获取焦点
                }
                int[] location = new int[2];
                int width = popupWindow.getContentView().getMeasuredWidth();
                codeIvSet.getLocationInWindow(location);
                int setWidth = codeIvSet.getWidth();
                popupWindow.showAtLocation(codeMainRl, Gravity.START | Gravity.TOP, location[0] - width, location[1] + 20);
        }

        @Override
        public void onClick(View v) {
                switch (v.getId()) {
                        case R.id.code_reset_ll:
                                CodeDataHelper.getInstance().resetCodeInfo();
                                startOtherActivity(CodeMarketingActivity.class, false);
                                popupWindow.dismiss();
                                break;
                        case R.id.code_del_ll:
                                popupWindow.dismiss();
                                showHintDialog(true);
                                break;
                        case R.id.guide_dialog_hint_sure:
                                hintDialog.dismiss();
                                if (mIsDel) {
                                        delMarketingData();
                                }
                                else {
                                        startOtherActivity(CodeMarketingActivity.class, false);
                                }
                                break;
                        case R.id.guide_dialog_hint_move:
                                hintDialog.dismiss();
                                if (!mIsDel) {
                                        finish();
                                }
                                break;
                }
        }

        @Override
        protected void onPause() {
                super.onPause();
                codeBgVp.removeCallbacks(runnable);
        }
}
